package com.qf.config;

import com.qf.properties.ElasticSearchProperties;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * create by 郑大仙丶
 * 2019/11/20 23:59
 */
@Configuration
public class ElasticSearchConfig {

    @Autowired
    private ElasticSearchProperties prop;

    private static final String SCHEME = "http";

    @Bean
    public RestHighLevelClient client(){
        //1. 获取配置文件的host信息
        String host = prop.getHost();
        //2. 如果是集群,用,分割
        String[] hosts = host.split(",");
        //3. 封装成一个集合
        List<HttpHost> hostList = new ArrayList<>();
        //4. 封装到集合中
        for (String s : hosts) {
            hostList.add(new HttpHost(s,prop.getPort(),SCHEME));
        }
        //5. 创建client对象
        RestClientBuilder builder = RestClient.builder(hostList.toArray(new HttpHost[0]));
        //6. 设置连接延迟配置.
        /*builder.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                builder.setConnectTimeout(prop.getConnectTimeout());
                builder.setSocketTimeout(prop.getSocketTimeout());
                builder.setConnectionRequestTimeout(prop.getConnectRequestTimeout());
                return builder;
            }
        });
        //7. 设置连接数配置.
        builder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder builder) {
                builder.setMaxConnTotal(prop.getMaxConnectNum());
                builder.setMaxConnPerRoute(prop.getMaxConnectPerRout());
                return builder;
            }
        });*/
        //8. 返回
        RestHighLevelClient client = new RestHighLevelClient(builder);
        return client;
    }
}
